#pragma once

#include <unordered_map>
#include "TcpServer.hpp"
#include "HttpProtocol.hpp"
#include "Session.hpp"

using namespace TcpServerModule;

class HttpServer;
using http_handler_t = std::function<void(HttpRequest& req, HttpResponse& resp, HttpServer&)>;

class HttpServer
{
public:
    HttpServer(int port)
    :_tsvr(std::make_unique<TcpServer>(port))
    ,_sm(std::make_unique<SessionManager>())
    {}

    void Start()
    {
        _tsvr->InitServer([this](SockPtr sockfd, InetAddr client){
            return this->HandlerHttpRequest(sockfd, client);
        });
        _tsvr->Loop();
    }

    void Register(const std::string& funcname, http_handler_t func)
    {
        _route[funcname] = func;
    }

    bool SafeCheck(const std::string& funcname)
    {
        auto iter = _route.find(funcname);
        if (iter == _route.end())
            return false;
        return true;
    }

    bool HandlerHttpRequest(SockPtr sockfd, InetAddr client)
    {
        LOG(LogLevel::INFO) << "HttpServer: get a new client: " << sockfd->Fd() << " addr info: " << client.Addr();
        std::string http_request;
        sockfd->Recv(&http_request);
        std::cout << client.Addr() << std::endl;
        std::cout << http_request << std::endl;

        HttpRequest req;
        req.Deserialize(http_request);
        HttpResponse resp;
        if (req.IsHasArgs())
        {
            std::string funcname = req.Path();
            if (SafeCheck(funcname))
                _route[req.Path()](req, resp, *this);
            else
                resp.Build(req);
        }
        else
        {
            resp.Build(req);
        }

        std::string http_response;
        resp.Serialize(&http_response);
        // std::cout << http_response << std::endl;
        sockfd->Send(http_response);



        // 读取请求，对请求进行分析处理 --->文本处理
        // 1.读取请求的完整性---暂时不做
        // 2.完整http反序列化,http reponse序列化

        // demo1: 直接返回一个固定的内容
        // std::string status_line = "HTTP/1.1 200 OK" + Sep;
        // std::string body_string = "<!DOCTYPE html>\
        //                             <html>\
        //                             <body>\
        //                                 Hello, World!\
        //                             </body>\
        //                             </html>";
        // std::string http_response = status_line + BlankLine + body_string;
        // sockfd->Send(http_response);
        return true;
    }

    ~HttpServer()
    {}
private:
    std::unique_ptr<TcpServer> _tsvr;
    std::unordered_map<std::string, http_handler_t> _route;  // 功能路由
    std::unique_ptr<SessionManager> _sm;
};